package com.aiatomic.couting.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.R;
import com.aiatomic.couting.models.TemplateEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;

public class SystemUtil {
    // 返回值 -1：没有网络 1：WIFI网络2：手机
    public static int GetNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 2;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    private static final String local_tpl = "local_tpl";

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机IMEI(需要“android.permission.READ_PHONE_STATE”权限)
     *
     * @return 手机IMEI
     */
    public static String getIMEI(Context ctx) {
        TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Activity.TELEPHONY_SERVICE);
        if (tm != null) {
            if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return "TODO";
            }
            return tm.getDeviceId();
        }
        return "";
    }

    public static String getAppVersion(Context ctx) {
        String pkName = ctx.getPackageName();
        try {
            String versionName = ctx.getPackageManager().getPackageInfo(pkName, 0).versionName;
            return versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "0.0.0";
    }

    public static String GetTemplateStoreDir(Context context) {
        return context.getExternalFilesDir(null) + File.separator + context.getString(R.string.dir_template_store);
    }

    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bf != null) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    public static void getAllLocalStoreTemplates(Context context, List<TemplateEntity> objects) {
        String string = (String) SPUtils.get(context, local_tpl, "");
        if (TextUtils.isEmpty(string)) {
            return;
        }
        Type type = new TypeToken<ArrayList<TemplateEntity>>() {
        }.getType();
        ArrayList<TemplateEntity> list = new Gson().fromJson(string, type);
        if (list != null) {
            objects.addAll(list);
        }

//		File templateDir = context.getExternalFilesDir(null);
//		if (templateDir.exists()) {
//			String[] cfgs = templateDir.list(new FilenameFilter() {
//
//				@Override
//				public boolean accept(File dir, String filename) {
//					return filename.endsWith(".cfg");
//				}
//			});
//			for (String cfg : cfgs) {
//				try {
//					JSONObject template = new JSONObject(
//							SystemUtil.getJson(context, templateDir.getAbsolutePath() + File.separator + cfg));
//					TemplateEntity object = new TemplateEntity();
//					object.setName(template.getString("name"));
//					object.setDesc(template.getString("desc"));
//					object.setDownload(true);
//					object.setGroup_id(template.getInt("group_id"));
//					object.setGroup_name(template.getString("group_name"));
//					object.setPic(template.getString("pic"));
//					object.setPlatform(template.getInt("platform"));
//					object.setPos(template.getInt("pos"));
//					object.setSb_template_id(template.getInt("sb_template_id"));
//					object.setType(template.getInt("type"));
//					object.setVersion(template.getString("version"));
//					object.setIs_recommend(template.getBoolean("is_recommend"));
//					object.settKey(template.getString("t_key"));
//					object.setShape(template.getString("shape"));
//					objects.add(object);
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//
//			}
//		}
    }

    public static void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }

	public static void saveTpl(Context context,List<TemplateEntity> oldList) {
		SPUtils.put(context,local_tpl,new Gson().toJson(oldList));
	}
}
